package com.itrui.user.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itrui.user.common.Code;
import com.itrui.user.common.CustomException;
import com.itrui.user.common.R;
import com.itrui.user.common.Result;
import com.itrui.user.pojo.Address;
import com.itrui.user.pojo.User;
import com.itrui.user.service.AddressService;
import com.itrui.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

/**
 * 模块：普通用户
 * 功能：登录，注册，查询信息（账号），修改信息，退出登录
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RefreshScope //nacos配置中心热更新
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${pattern.dateformat}")
    private String data;

    @Autowired
    private AddressService addressService;
    @GetMapping("/now")
    public String now(){
        /*return LocalDate.now().format(
          DateTimeFormatter.ofPattern(data, Locale.CANADA)
        );*/
        return data;
    }

    /**
     * 用户登录
     * @return
     */
    @PostMapping()
    public Result login(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //当前用户数据库是否存在
        queryWrapper.eq(User::getAccount, user.getAccount());
        User userLogin = userService.getOne(queryWrapper);
        //存在，查看登录状态
        if (userLogin != null) {
            if (userLogin.getStatus() == 0) {
                //登录验证
                if (user.getPassword().equals(userLogin.getPassword())) {
                    userLogin.setStatus(1);
                    userService.update(userLogin, queryWrapper);
                    return new Result(Code.GET_OK, userLogin, "登录成功");
                } else {
                    return new Result(Code.GET_ERR, "登录失败");
                }
            } else {
                //已登录，返回错误
                return new Result(Code.GET_ERR, "登录失败，已登录");
            }
        } else {
            //不存在，注册
            Random random = new Random();
            user.setName("易易用户" + random.nextInt());
            user.setCreateTime(LocalDateTime.now());
            boolean save = userService.save(user);
            return save ? new Result(Code.SAVE_OK, user, "注册成功") : new Result(Code.SAVE_ERR, "注册失败");
        }
    }



    /**
     * 用户信息
     * @param account
     * @return
     */
    @GetMapping("/{account}")
    public Result userInfo(@PathVariable int account) {
        //TODO 用户信息缓存redis
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getAccount, account);
        User byId = userService.getOne(queryWrapper);
        return new Result(Code.GET_OK, byId);
    }


    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PutMapping
    public Result ModifyUserInfo(@RequestBody User user) {
        System.out.println("接受的修改信息:" + user);
        if (user.getPassword() == null) {
            boolean b = userService.updateById(user);
            return b ? new Result(Code.UPDATE_OK,"修改成功") : new Result(Code.UPDATE_ERR,"修改失败");
        } else {
            //修改密码
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getAccount, user.getAccount());
            User userUpdate = userService.getOne(queryWrapper);
            if (user.getPassword().equals(userUpdate.getPassword())) {
                //修改密码
                userUpdate.setUpdateTime(LocalDateTime.now());
                userUpdate.setPassword(user.getUpdatePassword());
                userService.updateById(userUpdate);
                return new Result(Code.UPDATE_OK,"修改成功");
            } else {
                return new Result(Code.UPDATE_ERR,"密码错误");
            }
        }
    }



    /**
     * 更改账户余额
     * @param
     * @param
     * @return
     */
    /*@PutMapping("/umoney/{id}/{m}")
    public Boolean updateMoney(@PathVariable("id") Long id, @PathVariable("m") Float m){
        User user = userService.getById(id);
        Float _money = user.getMoney();
        Float money = _money - m;
        if (money < 0){
            return false;
        } else {
            user.setMoney(money);
            userService.updateById(user);
            return true;
        }

    }*/

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "orderUser.queue"),
            exchange = @Exchange(name = "itrui.direct", type = ExchangeTypes.DIRECT),
            key = "user"
    ))
    public void updateMoney(Map<String,Object> msg){
        User user = new User();
        Float _money = user.getMoney();
        Double money = (Double)msg.get("money");
        if (_money - money > 0){
            Long userId = (Long)msg.get("user");
            user.setId(userId);
            userService.updateById(user);
        }else{
            throw new CustomException("用户余额不足");
        }
    }


    @PostMapping("/add")
    public R<String> saveAddress(@RequestBody Address address){
        log.info("保存地址的信息："+address);

        boolean save = addressService.save(address);

        return save?R.success("成功"):R.error("失败");
    };

    /**
     * 获取用户地址
     * @param uid
     * @return
     */
    @GetMapping("/add/{uid}")
    public R<List<Address>> getAllAddressByAccount(@PathVariable Long uid){

        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId,uid);
        List<Address> list = addressService.list(queryWrapper);

        return R.success(list);

    };

    /**
     * 删除地址
     * @param id
     * @return
     */
    @DeleteMapping("/add/{id}")
    public R<String> delAddressById(@PathVariable Long id){

        boolean b = addressService.removeById(id);
        return  b?R.success("删除成功"):R.error("删除失败");
    };

    /**
     * 修改地址
     * @param address
     * @return
     */
    @PutMapping("/add")
    public R<String> updateAddress(@RequestBody Address address){
        log.info("修改的地址信息："+address);

        boolean flag = addressService.updateById(address);

        return flag?R.success("修改成功"):R.error("修改失败");
    };



}
